package com.zhang.chatcenter.manager.impl;

import com.alibaba.fastjson2.JSON;
import com.zhang.chatcenter.chat.ChannelHold;
import com.zhang.chatcenter.chat.ChatMessage;
import com.zhang.chatcenter.common.model.enums.RoomTypeEnums;
import com.zhang.chatcenter.manager.IMessageManager;
import com.zhang.chatcenter.service.chat.IChatService;
import com.zhang.chatcenter.service.chat.IRoomService;
import com.zhang.infrastructure.model.KingHoodExceptionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2024-03-19 16:45
 **/
@RequiredArgsConstructor
@Slf4j
@Service
public class MessageManager implements IMessageManager {

    private final IChatService chatService;
    private final IRoomService roomService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void read(ChannelHandlerContext ctx, String receivedMessage) {

        log.info("MessageManager=====》收到消息：{}", receivedMessage);
        // 解析成对象
        ChatMessage chatMessage = getChatMessage(receivedMessage);
        if (chatMessage == null) {
            return;
        }
        KingHoodExceptionUtil.isNull(chatMessage.getUserId(),"userId为null");

        // 分析消息
        switch (chatMessage.getCode()) {
            case "user":
                Channel channel = ctx.channel();
                ChannelHold.USER_CHANNEL.put(chatMessage.getUserId(),channel);
                log.info("绑定用户：{}",chatMessage.getUserId());
                break;
            case "single":
                List<Long> singleList = chatMessage.getToList();
                KingHoodExceptionUtil.isEmpty(singleList,"人员不能为空");
                KingHoodExceptionUtil.trueThrows(singleList.size() > 1,"单人聊天最多一个人在内");

                Long singleId = roomService.newRoom(chatMessage,RoomTypeEnums.SINGLE);
                roomService.addMessage(singleId,chatMessage.getUserId(),chatMessage.getMessage());
                chatService.send(chatMessage,chatMessage.getToList());
                log.info("单人聊天，消息：{}", chatMessage);
                break;
            case "new":
                // 新建房间，前端需要锁定只能开一个窗口或者采用http请求
                KingHoodExceptionUtil.isEmpty(chatMessage.getToList(), "人员数据不能为空");
                Long roomId = null;
                if (Objects.equals(chatMessage.getToList().size(), 1)) {
                    log.info("创建单人聊天");
                    roomId = roomService.newRoom(chatMessage, RoomTypeEnums.SINGLE);
                } else {
                    log.info("创建多人群聊");
                    roomId = roomService.newRoom(chatMessage, RoomTypeEnums.MULTIPLE);
                }

                ChannelHold.ROOM.put(roomId,chatMessage.getToList());
                log.info("创建房间：{}，消息：{}",roomId, chatMessage);
                ctx.writeAndFlush(new TextWebSocketFrame(roomId.toString()));
                break;

            case "room":
                // 房间聊天
                roomService.addMessage(chatMessage.getRoomId(),chatMessage.getUserId(),chatMessage.getMessage());

                List<Long> toList = ChannelHold.ROOM.get(chatMessage.getRoomId());
                chatService.send(chatMessage,toList);
                log.info("房间聊天，消息：{}", chatMessage);
                break;

            default:
        }
    }

    /**
     * 转化消息
     * */
    private ChatMessage getChatMessage(String receivedMessage) {

        try {
            ChatMessage chatMessage = JSON.parseObject(receivedMessage, ChatMessage.class);
            if (Objects.isNull(chatMessage) || ObjectUtils.isEmpty(chatMessage.getCode())) {
                log.error("异常消息：{}",receivedMessage);
                return null;
            }
            return chatMessage;
        } catch (Exception e){
            log.error("消息解析出现异常：{},异常信息：",receivedMessage,e);
            return null;
        }
    }
}
